<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>认识数字</title>
    <style>
        :root {
            --natural-color: #FF6B6B;
            --integer-color: #4D96FF;
            --rational-color: #6BCB77;
            --real-color: #B088F9;
            --irrational-color: #FFC107;
        }

        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #f6f8ff 0%, #f1f1f9 100%);
        }

        .container {
            display: flex;
            height: 600px;
            min-height: 500px;
            padding: 15px;
            gap: 20px;
        }

        .left-panel {
            flex: 0 0 450px;
            background: white;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .right-panel {
            flex: 1;
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
            font-size: 22px;
        }

        .venn-diagram {
            position: relative;
            width: 400px;
            height: 500px;
            margin: 0 auto;
        }

        .number-set {
            position: absolute;
            border: 3px solid;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            opacity: 0.8;
            font-weight: bold;
            color: #333;
        }

        .number-set:hover {
            opacity: 1;
            transform: scale(1.02);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .number-set.active {
            opacity: 1;
            transform: scale(1.02);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        #real-numbers {
            width: 360px;
            height: 460px;
            background-color: rgba(176, 136, 249, 0.1);
            border-color: var(--real-color);
            top: 20px;
            left: 20px;
        }

        #rational-numbers {
            width: 280px;
            height: 280px;
            background-color: rgba(107, 203, 119, 0.1);
            border-color: var(--rational-color);
            top: 60px;
            left: 60px;
        }

        #integers {
            width: 200px;
            height: 200px;
            background-color: rgba(77, 150, 255, 0.1);
            border-color: var(--integer-color);
            top: 100px;
            left: 100px;
        }

        #natural-numbers {
            width: 120px;
            height: 120px;
            background-color: rgba(255, 107, 107, 0.1);
            border-color: var(--natural-color);
            top: 140px;
            left: 140px;
        }

        #irrational-numbers {
            width: 280px;
            height: 80px;
            background-color: rgba(255, 193, 7, 0.1);
            border-color: #FFC107;
            bottom: 60px;
            left: 60px;
        }

        .content-area {
            display: none;
            animation: fadeIn 0.3s ease-in-out;
        }

        .content-area.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .content-title {
            color: #333;
            font-size: 24px;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #eee;
        }

        .content-description {
            color: #666;
            font-size: 15px;
            line-height: 1.5;
            margin-bottom: 20px;
        }

        .number-line {
            width: 100%;
            height: 140px;
            background: #fff;
            border-radius: 10px;
            margin-top: 15px;
        }

        .welcome-content {
            text-align: center;
            color: #666;
            padding: 40px 0;
        }

        .welcome-content h2 {
            color: #333;
            margin-bottom: 15px;
        }

        .welcome-content p {
            font-size: 15px;
            line-height: 1.6;
        }

        .number-set span {
            position: absolute;
            border-radius: 4px;
            white-space: nowrap;
            top: 10px;
            left: 10px;
        }

        #real-numbers span {
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
        }

        #rational-numbers span {
            right: 20px;
        }

        #integers span {
            left: 20px;
        }

        #natural-numbers span {
            left: 50%;
            transform: translateX(-50%);
        }

        .practice-container {
            margin: 20px 15px;
            margin-bottom: 80px;
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .practice-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .practice-header h2 {
            margin: 0;
            font-size: 20px;
            color: #333;
        }

        .btn-generate {
            background-color: var(--real-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-generate:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .welcome-practice {
            text-align: center;
            color: #666;
            padding: 40px 0;
        }

        .question-item {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 8px;
        }

        .question-title {
            font-size: 16px;
            color: #333;
            margin-bottom: 15px;
        }

        .options-list {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            padding: 0;
            margin: 0;
        }

        .option-item {
            margin: 0;
        }

        .option-item label {
            display: flex;
            align-items: center;
            cursor: pointer;
            padding: 5px;
            border-radius: 6px;
            transition: all 0.2s;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid #eee;
        }

        .option-item label:hover {
            background-color: #e9ecef;
            transform: translateY(-1px);
        }

        .option-item input[type="radio"] {
            margin-right: 10px;
        }

        .option-item input[type="radio"]:checked + span {
            color: var(--real-color);
            font-weight: 500;
        }

        .option-item label:has(input[type="radio"]:checked) {
            background-color: rgba(176, 136, 249, 0.1);
            border-color: var(--real-color);
        }

        .option-item .katex {
            display: inline-flex;
            align-items: center;
        }

        .result-area {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            background-color: rgba(248, 249, 250, 0.9);
        }

        .score {
            font-size: 24px;
            color: var(--real-color);
            text-align: center;
            margin-bottom: 15px;
        }

        .feedback {
            color: #666;
            line-height: 1.6;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .loading::after {
            content: '...';
            animation: dots 1.5s steps(4, end) infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60% { content: '...'; }
            80%, 100% { content: ''; }
        }

        .katex {
            font-size: 1.1em;
        }

        .feedback {
            white-space: pre-line;
        }

        .submit-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .submit-container .btn-generate {
            min-width: 120px;
        }

        /* 滚动条美化 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #999;
        }

        /* 练习区域的滚动设置 */
        .practice-content {
            overflow-y: auto;
        }

        /* 结果区域的滚动设置 */
        .result-area {
            overflow-y: auto;
            scroll-behavior: smooth;
        }

        /* 为选项添加半透明背景 */
        .option-item label {
            background-color: rgba(255, 255, 255, 0.9);
        }

        /* 结果区域的背景也调整为半透明 */
        .result-area {
            background-color: rgba(248, 249, 250, 0.9);
        }
    </style>
    <!-- KaTeX CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
    <!-- KaTeX JS -->
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
    <!-- KaTeX Auto-render Extension -->
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="left-panel">
            <h1>数字的分类体系</h1>
            <div class="venn-diagram">
                <div class="number-set" id="real-numbers"><span>实数 R</span></div>
                <div class="number-set" id="rational-numbers"><span>有理数 Q</span></div>
                <div class="number-set" id="integers"><span>整数 Z</span></div>
                <div class="number-set" id="natural-numbers"><span>自然数 N</span></div>
                <div class="number-set" id="irrational-numbers"><span>无理数 I</span></div>
            </div>
        </div>

        <div class="right-panel">
            <div class="welcome-content" id="welcome">
                <h2>欢迎探索数字世界</h2>
                <p>点击左侧的集合，了解不同类型的数字及其特点</p>
            </div>
            
            <div class="content-area" id="content">
                <h2 class="content-title" id="content-title"></h2>
                <p class="content-description" id="content-description"></p>
                <canvas class="number-line" id="number-line"></canvas>
            </div>
        </div>
    </div>

    <div class="practice-container">
        <div class="practice-header">
            <h2>练习题</h2>
            <button class="btn-generate" id="generateQuestions">生成新题目</button>
        </div>
        <div class="practice-content" id="practiceContent">
            <div class="welcome-practice" id="welcomePractice">
                <p>点击"生成新题目"开始练习</p>
            </div>
            <div class="questions-area" id="questionsArea" style="display: none;">
                <!-- 题目将通过 JavaScript 动态加载 -->
            </div>
            <div class="result-area" id="resultArea" style="display: none;">
                <!-- 结果将通过 JavaScript 动态显示 -->
            </div>
        </div>
    </div>

    <script>
        const numberSets = {
            'natural-numbers': {
                title: '自然数',
                description: '自然数是从1开始的正整数序列。它们是最基本的计数数字，用于表示物体的数量。\n\n特点：\n• 从1开始，无限延伸\n• 可以进行加法和乘法运算\n• 每个自然数都有唯一的后继数\n\n例如：1, 2, 3, 4, 5, ...',
                examples: [1, 2, 3, 4, 5],
                color: getComputedStyle(document.documentElement).getPropertyValue('--natural-color')
            },
            'integers': {
                title: '整数',
                description: '整数包括所有正整数、负整数和零。它们是在自然数的基础上，为了表示负值和零而扩展出来的数系。\n\n特点：\n• 包括负数、零和正数\n• 可以进行四则运算\n• 整数之间的减法运算结果仍是整数\n\n例如：..., -2, -1, 0, 1, 2, ...',
                examples: [-2, -1, 0, 1, 2],
                color: getComputedStyle(document.documentElement).getPropertyValue('--integer-color')
            },
            'rational-numbers': {
                title: '有理数',
                description: '有理数是可以表示为两个整数之比的数。它们包括所有整数和分数。\n\n特点：\n• 可以写成分数形式（p/q，其中q≠0）\n• 可以表示为有限小数或循环小数\n• 在数轴上稠密分布\n\n例如：1/2 (-0.5), 3/4 (0.75), 5/2 (2.5)',
                examples: [-1.5, -1, -0.5, 0, 0.5, 1, 1.5],
                color: getComputedStyle(document.documentElement).getPropertyValue('--rational-color')
            },
            'real-numbers': {
                title: '实数',
                description: '实数包括所有有理数和无理数。它们可以表示数轴上的任意一点。\n\n特点：\n• 包括有理数和无理数\n• 可以表示任意长度和距离\n• 在数轴上连续分布\n\n常见的无理数：π (3.14159...), √2 (1.41421...)',
                examples: [-3.14, -1.414, 0, 1.414, 3.14],
                color: getComputedStyle(document.documentElement).getPropertyValue('--real-color')
            },
            'irrational-numbers': {
                title: '无理数',
                description: '无理数是不能表示为两个整数之比的实数。它们是实数中除去有理数以外的所有数。\n\n特点：\n• 不能写成分数形式\n• 表示为无限不循环小数\n• 在数轴上处处稠密\n\n著名的无理数：π, e, √2, φ(黄金分割比)',
                examples: [-3.14159, -1.41421, 0, 1.41421, 3.14159],
                color: getComputedStyle(document.documentElement).getPropertyValue('--irrational-color')
            }
        };

        function drawNumberLine(canvas, numbers, color) {
            const ctx = canvas.getContext('2d');
            const width = canvas.width = canvas.offsetWidth;
            const height = canvas.height = canvas.offsetHeight;
            
            // 设置高清显示
            const dpr = window.devicePixelRatio || 1;
            canvas.style.width = width + 'px';
            canvas.style.height = height + 'px';
            canvas.width = width * dpr;
            canvas.height = height * dpr;
            ctx.scale(dpr, dpr);
            
            // 清空画布
            ctx.clearRect(0, 0, width, height);
            
            // 绘制数轴
            ctx.beginPath();
            ctx.moveTo(50, height/2);
            ctx.lineTo(width-50, height/2);
            ctx.strokeStyle = '#666';
            ctx.lineWidth = 2;
            ctx.stroke();
            
            // 绘制箭头
            ctx.beginPath();
            ctx.moveTo(width-50, height/2);
            ctx.lineTo(width-60, height/2-10);
            ctx.lineTo(width-60, height/2+10);
            ctx.fillStyle = '#666';
            ctx.fill();
            
            // 计算刻度间距
            const range = Math.max(...numbers) - Math.min(...numbers);
            const scale = (width-100) / range;
            const min = Math.min(...numbers);
            
            // 绘制刻度和数字
            numbers.forEach(num => {
                const x = 50 + (num - min) * scale;
                
                // 绘制刻度线
                ctx.beginPath();
                ctx.moveTo(x, height/2-10);
                ctx.lineTo(x, height/2+10);
                ctx.strokeStyle = '#666';
                ctx.lineWidth = 2;
                ctx.stroke();
                
                // 绘制数字点
                ctx.beginPath();
                ctx.arc(x, height/2, 6, 0, Math.PI * 2);
                ctx.fillStyle = color;
                ctx.fill();
                
                // 绘制数字
                ctx.fillStyle = '#333';
                ctx.font = '14px Arial';
                ctx.textAlign = 'center';
                ctx.fillText(num.toString(), x, height/2+30);
            });
        }

        // 事件处理
        document.querySelectorAll('.number-set').forEach(set => {
            set.addEventListener('click', () => {
                // 移除其他活动状态
                document.querySelectorAll('.number-set').forEach(s => s.classList.remove('active'));
                set.classList.add('active');

                const info = numberSets[set.id];
                
                // 隐藏欢迎信息
                document.getElementById('welcome').style.display = 'none';
                
                // 显示内容区域
                const content = document.getElementById('content');
                content.style.display = 'block';
                
                // 更新内容
                document.getElementById('content-title').textContent = info.title;
                document.getElementById('content-description').innerHTML = info.description.replace(/\n/g, '<br>');
                
                // 绘制数轴
                const canvas = document.getElementById('number-line');
                drawNumberLine(canvas, info.examples, info.color);
            });
        });

        // 添加练习相关的代码
        const generateQuestions = async () => {
            const questionsArea = document.getElementById('questionsArea');
            const welcomePractice = document.getElementById('welcomePractice');
            const resultArea = document.getElementById('resultArea');
            const generateBtn = document.getElementById('generateQuestions');

            // 显示加载状态
            welcomePractice.style.display = 'none';
            resultArea.style.display = 'none';
            questionsArea.style.display = 'block';
            questionsArea.innerHTML = '<div class="loading">正在生成题目</div>';
            generateBtn.disabled = true;

            try {
                // 获取当前选中的数字类型
                const activeSet = document.querySelector('.number-set.active');
                if (!activeSet) {
                    alert('请先选择一个数字类型');
                    generateBtn.disabled = false;
                    return;
                }

                const selectedType = numberSets[activeSet.id];
                
                const prompt = `请生成5道关于${selectedType.title}的选择题，包括2个概念认识题、2个计算题和1个应用题。

知识范围：
${selectedType.description.replace(/\n/g, ' ')}

要求：
1. 每道题必须有4个选项(A、B、C、D)
2. 必须包含正确答案
3. 难度适中
4. 题目必须紧密结合${selectedType.title}的特点和性质
5. 可以使用 LaTeX 数学公式，用 \\( \\) 包裹行内公式，用 \\[ \\] 包裹独立公式
6. 概念题应该考察${selectedType.title}的定义和性质
7. 计算题应该使用${selectedType.title}范围内的数字
8. 应用题要体现${selectedType.title}在实际中的应用

返回格式：
## 题目
1. [第1题]
   A. [选项A]
   B. [选项B]
   C. [选项C]
   D. [选项D]

... (其他题目)

## 答案
1. [答案]
...

## 解析
1. [解析]
...`;

                const response = await fetch('/api/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        messages: [{
                            role: 'user',
                            content: prompt
                        }],
                        stream: true
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let markdown = '';
                let questions = [];
                let answers = [];
                let explanations = [];

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(5));
                                if (data.content) {
                                    markdown += data.content;
                                    // 实时更新显示
                                    const formattedContent = parseMarkdown(markdown);
                                    questionsArea.innerHTML = formattedContent;
                                    // 修改滚动逻辑
                                    window.scrollTo({
                                        top: document.documentElement.scrollHeight,
                                        behavior: 'smooth'
                                    });
                                }
                            } catch (e) {
                                console.error('Error parsing JSON:', e);
                            }
                        }
                    }
                }

                // 修改添加提交按钮的部分
                const submitContainer = document.createElement('div');
                submitContainer.className = 'submit-container';
                
                const submitBtn = document.createElement('button');
                submitBtn.className = 'btn-generate';
                submitBtn.textContent = '提交答案';
                
                submitContainer.appendChild(submitBtn);
                questionsArea.appendChild(submitContainer);

                submitBtn.addEventListener('click', () => {
                    const selectedAnswers = [];
                    const questionElements = questionsArea.querySelectorAll('.question-item');
                    questionElements.forEach((question, index) => {
                        const selected = question.querySelector('input[type="radio"]:checked');
                        selectedAnswers.push(selected ? selected.value : null);
                    });

                    // 解析答案和计算分数
                    const correctAnswers = markdown.match(/## 答案\n([\s\S]*?)(?=\n## |$)/)[1]
                        .split('\n')
                        .filter(line => line.trim())
                        .map(line => line.replace(/^\d+\.\s*/, '').trim());

                    const explanationsText = markdown.match(/## 解析\n([\s\S]*?)(?=\n## |$)/)[1]
                        .split('\n')
                        .filter(line => line.trim())
                        .map(line => line.replace(/^\d+\.\s*/, '').trim());

                    let score = 0;
                    const feedback = selectedAnswers.map((answer, index) => {
                        const isCorrect = answer === correctAnswers[index];
                        if (isCorrect) score += 20;
                        return `第${index + 1}题: ${isCorrect ? '✓' : '✗'}\n解析: ${explanationsText[index]}`;
                    });

                    // 显示结果
                    resultArea.style.display = 'block';
                    resultArea.innerHTML = `
                        <div class="score">得分：${score}</div>
                        <div class="feedback">${feedback.join('\n\n').replace(/\n/g, '<br>')}</div>
                    `;

                    // 渲染结果区域中的数学公式
                    renderMathInElement(resultArea, {
                        delimiters: [
                            {left: "\\(", right: "\\)", display: false},
                            {left: "\\[", right: "\\]", display: true},
                            {left: "$", right: "$", display: false},
                            {left: "$$", right: "$$", display: true}
                        ],
                        throwOnError: false
                    });

                    // 修改结果显示后的滚动逻辑
                    setTimeout(() => {
                        resultArea.scrollIntoView({ 
                            behavior: 'smooth', 
                            block: 'center'  // 改为 center 以确保完全可见
                        });
                    }, 100);  // 添加小延时确保内容已渲染
                });

            } catch (error) {
                questionsArea.innerHTML = `<div class="error">生成题目时出错：${error.message}</div>`;
            } finally {
                generateBtn.disabled = false;
            }
        };

        function parseMarkdown(markdown) {
            // 提取题目部分
            const questionsMatch = markdown.match(/## 题目\n([\s\S]*?)(?=\n## |$)/);
            if (!questionsMatch) return markdown;

            const questionsText = questionsMatch[1];
            const questions = questionsText.split('\n\n').filter(q => q.trim());

            const html = questions.map((question, index) => {
                const lines = question.split('\n').filter(line => line.trim());
                const title = lines[0].replace(/^\d+\.\s*/, '');
                const options = lines.slice(1).map(line => {
                    const [label, ...text] = line.trim().split('. ');
                    return {
                        label,
                        text: text.join('. ')
                    };
                });

                return `
                    <div class="question-item">
                        <div class="question-title">${index + 1}. ${title}</div>
                        <div class="options-list">
                            ${options.map(option => `
                                <div class="option-item">
                                    <label>
                                        <input type="radio" name="question${index}" value="${option.label}">
                                        <span>${option.label}. ${option.text}</span>
                                    </label>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }).join('');

            const container = document.createElement('div');
            container.innerHTML = html;

            // 渲染数学公式
            renderMathInElement(container, {
                delimiters: [
                    {left: "\\(", right: "\\)", display: false},
                    {left: "\\[", right: "\\]", display: true},
                    {left: "$", right: "$", display: false},
                    {left: "$$", right: "$$", display: true}
                ],
                throwOnError: false
            });

            return container.innerHTML;
        }

        document.getElementById('generateQuestions').addEventListener('click', () => {
            const activeSet = document.querySelector('.number-set.active');
            if (!activeSet) {
                alert('请先选择一个数字类型再生成题目');
                return;
            }
            generateQuestions();
        });
    </script>
</body>
</html> 